__author__ = 'aesop'
#coding:utf-8
import libs.util.redis_queue as redis_queue
import libs.weixinApi.get_openid_oauth2 as get_openid_oauth2
from flask import request
from flask import session
import json

def scan_qr(app):
    @app.route('/backstage/login/waiting')
    def waiting_response():
        temp_code = request.args.get('code')
        sub = redis_queue.sub(temp_code)
        count = 0
        for m in sub.listen():
            if(count > 0):
                return str(m['data'])
            count +=1

    @app.route('/backstage/login/callback')
    def wx_callback():
        code = request.args.get("code")
        state = request.args.get("state")

        openid_dic = get_openid_oauth2(code)
        if(openid_dic["err"] == "0"):
            openid = openid_dic["openid"]
            session["openid"] = openid
            dic = {
                "errCode" : 0,
                "description":"Scan successful!"
            }
            redis_queue.pub(state,json.dumps(dic))
            return ''
        else:
            return ''